#coding=utf-8
import jieba
import jieba.posseg as pseg
import matplotlib.pyplot as plt
import re
def read_file_gbk(filename):
    with open(filename,'r',encoding='GBK') as f:
        s = f.read()
        s = re.sub('/C', '', s)
        s = re.sub('\r|\n|\s','',s)
    return s
def caculate(text):
    s= read_file_gbk(text)
    noun_list = []
    wordlist = pseg.lcut(s)
    for x, y in wordlist:
        if y == 'n':
            noun_list.append(x)
    noun_bili = float(len(noun_list) / len(wordlist))
    verb_list = []
    wordlist = pseg.lcut(s)
    for x, y in wordlist:
        if y == 'v':
            verb_list.append(x)
    verb_bili = float(len(verb_list) / len(wordlist))
    adj_list = []
    wordlist = pseg.lcut(s)
    for x, y in wordlist:
        if y == 'a':
            adj_list.append(x)
    adj_bili = float(len(adj_list) / len(wordlist))
    x_data = ["名词", "动词", "形容词","其它词"]
    y_data = [len(noun_list),len(verb_list),len(adj_list),len(wordlist)-len(noun_list)-len(verb_list)-len(adj_list)]

    bar_width = 0.3

    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
    # 将X轴数据改为使用range(len(x_data), 就是0、1、2...
    plt.pie(y_data, labels=x_data, autopct='%.0f%%')

    # 设置标题
    plt.title("词性比例计算")
    # 为两条坐标轴设置名称

    # 显示图例
    plt.legend()
    plt.show()
    print("Over!")

caculate("XX.txt")
caculate("YQ.txt")